package com.example.app.manager.websocket

import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.LanguageUtils
import com.example.app.global.GlobalUserManager
import com.example.app.manager.websocket.socket.BusinessSocketClient
import com.example.app.manager.websocket.socket.SocketURL

/**
 * Created on 2022/9/8.
 * @author Joker
 * Des:接收数据 LiveEventManager.observe(owner, EventBusinessSocket::class.java) {}
 */

class BusinessManager {

    companion object {
        val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { BusinessManager() }
    }

    private var businessSocketClient: BusinessSocketClient? = null
    private var lastConnectTime = 0L

    /**
     * 开始链接
     */
    fun startConnect() {
        //1、检查是否已连接 / 是否未登录 / 防抖动多次启动
        val curTime = System.currentTimeMillis()
        if (isSocketConnected() || !GlobalUserManager.isLogin() || (curTime - lastConnectTime < 1500L)) return
        lastConnectTime = curTime

        //2、创建连接
        closeSocket()
        businessSocketClient = BusinessSocketClient(SocketURL.URL_BUSINESS + getCommonParam())
        businessSocketClient?.connectionLostTimeout = 20
        businessSocketClient?.connect()
    }

    fun checkAndReconnectSocket() {
        if (GlobalUserManager.isLogin() && !isSocketConnected()) {
            startConnect()
        }
    }

    /**
     * 关闭连接
     */
    fun closeSocket() {
        businessSocketClient?.close()
        businessSocketClient = null
    }

    /**
     * 发送消息
     */
    fun doSendMsg(data: String?) {
        businessSocketClient?.doSendMsg(data)
    }

    /**
     * 子线程中发送
     */
    fun doSendHeartBeat() {
        if (isSocketConnected() && GlobalUserManager.getUid() > 0) {
            //doSendMsg(SendSocketEntity(EventBusinessSocket.TYPE_HEART_BIT, Payload(AppUtils.isAppForeground()), TimeUtils.getNowMills(), BaseSocketClient.generateWebSocketTraceId()).toJson())
        }
    }

    /**
     * 长链是否连着
     */
    fun isSocketConnected() = businessSocketClient?.isOpen == true

    /**
     * 公共参数
     */
    fun getCommonParam(): String = ("?uid=${GlobalUserManager.getUid()}" +
            "&app=HAPPYCHAT" +
            "&platform=android" +
            "&version=${AppUtils.getAppVersionName()}" +
            "&system_version=${DeviceUtils.getSDKVersionName()}" +
            "&manufacturer=${DeviceUtils.getManufacturer()}" +
            "&model=${DeviceUtils.getModel()}" +
            "&unique=${DeviceUtils.getUniqueDeviceId()}" +
            "&language=${LanguageUtils.getSystemLanguage().language}" +
            "&os_version=${DeviceUtils.getSDKVersionName()}" +
            "&sys_language=${LanguageUtils.getSystemLanguage().language}" +
            "&country=${LanguageUtils.getSystemLanguage().country}"
            ).replace(" ", "%20").replace("'", "%27")
}